package com.owl.jdbc.aop;


import com.owl.jdbc.aop.annotation.DataSourceSelector;
import com.owl.jdbc.context.DBContextHolder;
import com.owl.jdbc.enums.DataSourceType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
@Order(value = 1)
public class DataSourceAop {


    @Around("@annotation(com.owl.jdbc.aop.annotation.DataSourceSelector)")
    public Object dataSourceSelectorAnnotation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Method method = this.getMethod(proceedingJoinPoint);
        DataSourceSelector dataSourceImport = method.getAnnotation(DataSourceSelector.class);
        if(dataSourceImport.value()== DataSourceType.MASTER)
        {
            DBContextHolder.set("master");
        }else if(dataSourceImport.value()== DataSourceType.SLAVE)
        {
            DBContextHolder.slave();
        }
        return proceedingJoinPoint.proceed();
    }




//
//    @Pointcut("execution(* com.baimeng.*.query*(..)) || execution(* com.baimeng.*.find*(..)) ||execution(* com.baimeng.*.select*(..))||execution(* com.baimeng.*.load*(..))")
//    public void slave()
//    {
//        DBContextHolder.slave();
//    }
//
//
//
//    @Pointcut("execution(* com.baimeng.*.save*(..)) || execution(* com.baimeng.*.update*(..)) || execution(* com.baimeng.*.delete*(..)) || execution(* com.baimeng.*.add*(..))|| execution(* com.baimeng.*.edit*(..))|| execution(* com.baimeng.*.remove*(..))")
//    public void master()
//    {
//        DBContextHolder.master();
//    }


    private Method getMethod(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        return signature.getMethod();
    }

}
